package de.dopichaj.labrador.search.hit;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.apache.commons.lang.StringEscapeUtils;
import org.xml.sax.Attributes;
import org.xml.sax.ContentHandler;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;

/**
 * Intermediate search results, where the hits from each document are stored
 * separately.
 * 
 * Key is the document path (as a File), the associated value is the Collection
 * of Hits from this document.
 */
public class DocHitMap {

    private final Map<File, Collection<Hit>> results; 

    public DocHitMap() {
        results = new HashMap<File, Collection<Hit>>();
    }
    
    /**
     * Read the result as written by writeResult.
     */
    public DocHitMap(InputStream in)
        throws ParserConfigurationException, SAXException, IOException {
        
        this();
        SAXParserFactory factory = SAXParserFactory.newInstance();
        SAXParser saxParser = factory.newSAXParser();
        XMLReader xmlReader = saxParser.getXMLReader();
        ResultHandler rh = new ResultHandler();
        xmlReader.setContentHandler(rh);
        xmlReader.parse(new InputSource(in));
    }
    
    /**
     * Write the result to a stream in XML format.
     * Does not write an XML header, so it can be embedded in other XML output.
     */
    public synchronized void writeResult(PrintWriter writer) {
        writer.println("<result>");
        for (Map.Entry<File, Collection<Hit>> entry : results.entrySet()) {
            writer.println("  <document path='" +
                StringEscapeUtils.escapeXml(entry.getKey().toString()) + "'>");
            for (Hit hit : entry.getValue()) {
                writer.println("    <hit " +
                    "xpath='" + StringEscapeUtils.escapeXml(hit.getXPath()) + "' " +
                    "length='" + hit.getContentLength() + "' " +
                    "pos='" + hit.getPosition() + "' " +
                    "score='" + hit.getScore() + "' " +
                    "/>");
            }
            writer.println("  </document>");
        }
        writer.println("</result>");
    }

    /**
     * A {@link ContentHandler} for the XML result serialization format. 
     */
    private final class ResultHandler extends DefaultHandler {
        
        private File currentPath;
        private Collection<Hit> currentHits;
        
        @Override
        public void startElement(String uri, String localName, String qName, Attributes attributes) {
            if (qName.equals("document")) {
                currentPath = new File(attributes.getValue("path"));
                currentHits = new HashSet<Hit>();
                results.put(currentPath, currentHits);
            } else if (qName.equals("hit")) {
                String xPath = attributes.getValue("xpath");
                int length = Integer.parseInt(attributes.getValue("length"));
                int pos = Integer.parseInt(attributes.getValue("pos"));
                float score = Float.parseFloat(attributes.getValue("score"));
                
                currentHits.add(new MemoryHit(currentPath, xPath, length, pos, score));
            }
        }
    }
    
    /**
     * Get a {@link ContentHandler} for reading serialized results into
     * <code>this</code>.
     * The returned handler only overrides <code>startElement</code> and only
     * handles elements with a <code>qName</code> of either <code>document</code>
     * or <code>hit</code>; it is thus sufficient to call it for all elements of
     * these types.
     */
    public ContentHandler getContentHandler() {
        return new ResultHandler();
    }
    
    /**
     * Get all the documents in this map.
     * The resulting set is a copy, so you may do whatever you want (including
     * modification).
     */
    public synchronized Set<File> getDocs() {
        Set<File> result = new HashSet<File>();
        result.addAll(results.keySet());
        return result;
    }

    /**
     * Get the hits for the given document
     * 
     * @return the corresponding hits (an empty collection if there are no
     * results from this document).
     */
    public synchronized Collection<Hit> getHitsFromDoc(File file) {
        if (results.containsKey(file)) {
            return results.get(file);
        } else {
            return Collections.emptyList();
        }
    }

    /**
     * Set the hits corresponding to a given document, replacing the original set.
     */
    public synchronized void setHitsFromDoc(File file, Collection<Hit> hits) {
        results.put(file, hits);
    }
    
    /**
     * Add a new hit to the hits for the corresponding document.
     */
    public synchronized void addHit(Hit hit) {
        Collection<Hit> hits = results.get(hit.getFile());
        if (hits == null) {
            hits = new HashSet<Hit>();
            results.put(hit.getFile(), hits);
        }
        hits.add(hit);
    }
    
    /**
     * Get a collection of all hit sets.
     */
    public synchronized Collection<Collection<Hit>> getHitSets() {
        return results.values();
    }
    
    /**
     * Merge the results from all documents into one sorted set of results,
     * ordering by the given Comparator.
     */
    public List<Hit> getSortedHits(Comparator<Hit> comparator) {
        List<Hit> sortedHits = getHits();
        Collections.sort(sortedHits, comparator);
        return sortedHits;
    }

    /**
     * Get the hits in random order. You may modify the list; it supports the
     * optional {@link List#remove(int)} operation.
     * @return the list of hits
     */
    public List<Hit> getHits() {
        List<Hit> allHits = new ArrayList<Hit>(results.size());
        for (Collection<Hit> hits : results.values()) {
            allHits.addAll(hits);
        }
        return allHits;
    }

    /**
     * Merge the results from all documents into one sorted set of results,
     * ordering by score.
     */
    public List<Hit> getSortedHits() {
        return getSortedHits(new HitComparator(HitComparator.SORT_BY_SCORE));
    }
}
/*
Copyright (c) 2005-2007 Philipp Dopichaj

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/